package ph.com.gs3.formalistics.presenter.fragments.views;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.global.utilities.view.ViewGroupUtils;
import ph.com.gs3.formalistics.model.vo.business.form.Form;
import ph.com.gs3.formalistics.services.managers.SessionManager;
import ph.com.gs3.formalistics.services.managers.SessionManager.Mode;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

@SuppressWarnings("deprecation")
public class MainViewFragment extends Fragment {

	// ========================================================================
	// {{ Constants

	public static final String PROMPT_NO_CONNECTION = "No connection to server";
	public static final String PROMPT_HAS_CONNECTION = "Connected to server";

	public static final String COLOR_ERROR = "#dbdbdb";
	public static final String COLOR_INFO = "#00d505";

	// }}

	// ========================================================================
	// {{ View Fields

	private List<Fragment> viewFragments;
	private List<ImageView> tabIcons;

	private Button bRetryConnection;

	private ViewPager vpMainViewPager;
	private ActionBar abMainActionBar;
	private Spinner spFormFilter;
	private LinearLayout llMessageContainer;
	private TextView tvMessageNotification;

	private LinearLayout llLoadingMessageContainer;
	private TextView tvLoadingMessage;

	private Animation fadeInAnimation, fadeOutAnimation;

	private ArrayAdapter<Form> formfilterAdapter;

	// }}

	// ========================================================================
	// {{ Local Fields

	private List<Form> formFilterSelection;

	private Form currentlySelectedFormFilter;

	private MainViewActivityActionListener listener;

	private SessionManager.Mode connectionMode;

	// }}

	public static MainViewFragment createInstance(List<Form> formFilterSelection,
	        List<Fragment> viewFragments, SessionManager.Mode connectionMode) {

		MainViewFragment instance = new MainViewFragment();
		instance.formFilterSelection = formFilterSelection;
		instance.connectionMode = connectionMode;
		instance.viewFragments = viewFragments;

		instance.resetFormFilterSelection();

		return instance;

	}

	// ========================================================================
	// {{ Life Cycle Listeners

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_main, container, false);

		initializeSpinnerTitleBar(rootView);

		// initializeViewAdapters(getActivity());
		initializeViewComponents(rootView);
		initializeViewPager(rootView);
		initializeTabIcons();
		initializeActionBarTabs();

		//
		// isFragmentViewInitialized = true;

		if (connectionMode == Mode.ONLINE) {
			notifyOnlineMode();
		} else {
			notifyOfflineMode();
		}

		listener.onViewReady();

		return rootView;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			listener = (MainViewActivityActionListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
			        + " must implement MainViewActivityActionListener");
		}
	}

	// }}

	// ========================================================================
	// {{ Initializer Methods

	private void initializeViewComponents(View rootView) {

		// Bottom Notification Views
		llMessageContainer = (LinearLayout) rootView.findViewById(R.id.Main_llMessageContainer);
		llMessageContainer.setVisibility(View.GONE);

		tvMessageNotification = (TextView) rootView.findViewById(R.id.Main_tvMessage);

		bRetryConnection = (Button) rootView.findViewById(R.id.Main_bRetry);
		bRetryConnection.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				listener.onRetryConnectionRequested();
			}

		});
	}

	private void initializeViewPager(View rootView) {
		vpMainViewPager = (ViewPager) rootView.findViewById(R.id.Main_vpMainViewPager);
		vpMainViewPager.setAdapter(new MainViewPagerAdapter(getFragmentManager()));
		vpMainViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

			@Override
			public void onPageSelected(int index) {
				abMainActionBar.setSelectedNavigationItem(index);
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {}
		});
	}

	private void initializeTabIcons() {

		ImageView ivHome = new ImageView(getActivity());
		ivHome.setImageResource(R.drawable.home);

		ImageView ivMyapproval = new ImageView(getActivity());
		ivMyapproval.setImageResource(R.drawable.user_check);

		ImageView ivMyrequest = new ImageView(getActivity());
		ivMyrequest.setImageResource(R.drawable.forms);

		ImageView ivStarred = new ImageView(getActivity());
		ivStarred.setImageResource(R.drawable.starred);

		ImageView ivMypending = new ImageView(getActivity());
		ivMypending.setImageResource(R.drawable.pending);

		tabIcons = new ArrayList<ImageView>();

		tabIcons.add(ivHome);
		tabIcons.add(ivMyapproval);
		tabIcons.add(ivMyrequest);
		tabIcons.add(ivStarred);
		tabIcons.add(ivMypending);

	}

	private void initializeActionBarTabs() {

		abMainActionBar = getActivity().getActionBar();
		abMainActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		MainTabViewTabListener tabListener = new MainTabViewTabListener();

		for (int i = 0; i < viewFragments.size(); i++) {

			ActionBar.Tab tab = abMainActionBar.newTab();
			tab.setTabListener(tabListener);
			tab.setCustomView(tabIcons.get(i));

			abMainActionBar.addTab(tab);

		}

	}

	@SuppressLint("InflateParams")
	private void initializeSpinnerTitleBar(View rootView) {

		// Get the default title bar of the view
		int titleBarResourceId = Resources.getSystem().getIdentifier("action_bar_title", "id",
		        "android");
		View titleBarView = getActivity().findViewById(titleBarResourceId);

		// Initialize the spinner view that will replace the default title bar
		formfilterAdapter = new ArrayAdapter<Form>(getActivity(), R.layout.view_form_filter_item,
		        formFilterSelection);
		formfilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spFormFilter = (Spinner) getActivity().getLayoutInflater().inflate(
		        R.layout.view_form_filter_spinner, null);

		spFormFilter.setAdapter(formfilterAdapter);

		ViewGroupUtils.replaceView(titleBarView, spFormFilter);

		spFormFilter.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

				// Notify listener if the form filter has changed
				Form selectedForm = formFilterSelection.get(position);
				if (selectedForm.getId() != currentlySelectedFormFilter.getId()) {
					currentlySelectedFormFilter = selectedForm;
					listener.onFormFilterChanged(selectedForm);
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {}

		});

	}

	// }}

	// ========================================================================
	// {{ Functional Methods

	public void notifyOnlineMode() {

		tvMessageNotification.setText(PROMPT_HAS_CONNECTION);
		bRetryConnection.setVisibility(View.INVISIBLE);

		llMessageContainer.setAnimation(fadeInAnimation);
		llMessageContainer.setVisibility(View.VISIBLE);
		llMessageContainer.setBackgroundColor(Color.parseColor(COLOR_INFO));
		llMessageContainer.postDelayed(new Runnable() {

			@Override
			public void run() {
				llMessageContainer.setVisibility(View.GONE);
				llMessageContainer.setAnimation(fadeOutAnimation);
			}

		}, 5000);
	}

	public void notifyOfflineMode() {

		tvMessageNotification.setText(PROMPT_NO_CONNECTION);
		bRetryConnection.setVisibility(View.VISIBLE);
		llMessageContainer.setAnimation(fadeInAnimation);
		llMessageContainer.setVisibility(View.VISIBLE);
		llMessageContainer.setBackgroundColor(Color.parseColor(COLOR_ERROR));

	}

	public void resetFormFilterSelection() {

		if (formFilterSelection == null) {
			formFilterSelection = new ArrayList<Form>();
		} else {
			formFilterSelection.clear();
		}

		// Add an "All Forms" option with id = 0
		Form allFormsOption = new Form();
		allFormsOption.setId(0);
		allFormsOption.setName("All Forms");

		formFilterSelection.add(allFormsOption);
		currentlySelectedFormFilter = formFilterSelection.get(0);
	}

	public void addFormFilters(List<Form> forms) {

		for (Form form : forms) {
			formFilterSelection.add(form);
		}

		formfilterAdapter.notifyDataSetChanged();

	}

	// }}

	// ========================================================================
	// {{ Adapters and Event Implementation Private Classes

	private class MainViewPagerAdapter extends FragmentPagerAdapter {

		public MainViewPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int index) {
			return viewFragments.get(index);
		}

		@Override
		public int getCount() {
			return viewFragments.size();
		}

	}

	private class MainTabViewTabListener implements TabListener {

		@Override
		public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {}

		@Override
		public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {
			vpMainViewPager.setCurrentItem(tab.getPosition());
		}

		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {}

	}

	// }}

	// ========================================================================
	// Interfaces

	public static interface MainViewActivityActionListener {
		public void onViewReady();

		public void onFormFilterChanged(Form form);

		public void onRetryConnectionRequested();

	}

}
